import React, { useState, useEffect, useRef } from 'react'
import { useNavigate } from "react-router-dom";
import styles from '../../style/childPublic/childPublic.module.less'
import business from '../../style/BusinessEntity/BusinessEntity.module.less'
import pesticideDosageStyle from '../../style/pesticideDosage/pesticideDosage.module.less'
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import LeftNav from '../../components/LeftNav/LeftNav';
import { SearchOutlined } from '@ant-design/icons';
import { Input, Button, Pagination, message, Empty } from 'antd';
import { getGoodsList, getAreaList } from '../../apis/PesticideDosage'
export default function BusinessEntity() {
    const [messageApi, contextHolder] = message.useMessage();
    const key = 'updatable';
    const [title] = useState('农药用量统计监管平台');
    const [areaData, setAreaData] = useState({ pageNum: 1, goods_type_id: '', pageSize: '10', area_level: localStorage.getItem('areaLevel'), area_id: localStorage.getItem('areaId'), keywords: '' })
    const [leftNavList, setLeftNavList] = useState([])
    const [total, setTotal] = useState(0)
    const keyWordsRef = useRef();
    const [keyWords, setKeyWords] = useState('')
    const [currentId, setCurrentId] = useState('')
    const [contentListTitle, setContentListTitle] = useState([
        { id: 1, title: '农药名称' },
        { id: 2, title: '全县库存(kg)' },
        { id: 3, title: '全县上季度销售量(kg)' },
        { id: 4, title: '登记证号' },
        { id: 5, title: '临期库存' },
        { id: 6, title: '过期处理' },
    ])
    const [showId, setShowId] = useState(1)
    const [titleList] = useState([
        { id: 1, title: '农药分类' },
        { id: 2, title: '区域' },
    ])
    const [contentList, setContentList] = useState([])
    const [topList] = useState([
        { id: 1, back: require('../../assets/pesticide/psticide1.png'), title: '全类型农药库存', num: 0 },
        { id: 2, back: require('../../assets/pesticide/psticide2.png'), title: '全类型上季度销量', num: 0 },
        { id: 3, back: require('../../assets/pesticide/psticide3.png'), title: '全类型临期库存', num: 0 },
        { id: 4, back: require('../../assets/pesticide/psticide4.png'), title: '全类型过期库存', num: 0 },
    ])
    const [allWeight, setAllWeight] = useState('')
    const navigate = useNavigate()
    // 侧边栏
    const getClick = (data) => {

        if (showId === 1) {
            setCurrentId(data.id)
            getGoods({
                ...areaData,
                goods_type_id: data.id
            })
            topList.map(item => {
                switch (item.title) {
                    case '全类型农药库存':
                        item.title = `${data.name}农药库存`
                        return item;
                    case '全类型上季度销量':
                        item.title = `${data.name}上季度销量`
                        return item;
                    case '全类型临期库存':
                        item.title = `${data.name}临期库存`
                        return item;
                    default:
                        item.title = `${data.name}过期库存`
                        return item;
                }
            })

        } else {
            setCurrentId(data.id)
            setAreaData({
                ...areaData,
                area_level: data.area_level,
                area_id: data.id,
            })
        }
    }
    useEffect(() => {
        if (showId === 1) {
            getGoods(areaData)
        } else {
            getAreaListData(areaData)
        }
    }, [areaData, showId])
    const getGoods = async (res) => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getGoodsList(res)
        if (data.state === 1) {
            if (showId === 1) {
                let newArray = []
                let newObject = { name: '全部', id: '' }
                newArray = [...data.goodsTypeList, newObject]
                newArray.reverse()
                setLeftNavList(newArray)

            }
            setContentList(data.list)
            setTotal(data.count)

            topList.map(item => {
                switch (item.title) {
                    case '全类型农药库存':
                        item.num = data.allKucun
                        return item;
                    case '全类型上季度销量':
                        item.num = data.allOut
                        return item;
                    case '全类型临期库存':
                        item.num = data.allLinqi
                        return item;
                    default:
                        item.num = data.allGuoQi
                        return item;
                }
            })
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        }
    };
    // 侧边区域列表
    const getAreaListData = async (res) => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await getAreaList(res)
        if (data.state === 1) {
            let newArray = []
            let newObject = { name: '全部', id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') }
            newArray = [...data.areaList, newObject]
            newArray.reverse()
            setLeftNavList(newArray)
            setContentList(data.list)
            setAllWeight(data.all_weight)
            setTotal(data.count)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                type: 'error',
                content: data.msg,
            });
        }
    }
    // 切换页码
    const onChangePage = (page, pageSize) => {
        setAreaData({
            ...areaData,
            pageNum: page
        })
    };
    // 搜素
    const search = () => {
        setAreaData({
            ...areaData,
            keywords: keyWords
        })
        // 点击搜索后左侧选中状态回到全部
        setCurrentId('')
    };
    // 分页
    const itemRender = (_, type, originalElement) => {
        if (type === 'prev') {
            return <a>上一页</a>;
        }
        if (type === 'next') {
            return <a>下一页</a>;
        }
        return originalElement;
    };
    //左部顶部切换
    const showIdClick = (id) => {
        // 解决setSate同步的弊端示列
        // setShowId(id)
        // setShowId((pro) => {
        //     console.log("旧值", showId)
        //     return pro
        // })
        setCurrentId('')
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        setAreaData({
            ...areaData,
            keywords: ''
        })
        setKeyWords('')
        if (id === 1 && showId !== id) {
            setShowId(id)
            getGoods(areaData)
            setContentListTitle([
                { id: 1, title: '农药名称' },
                { id: 2, title: '全县库存(kg)' },
                { id: 3, title: '全县上季度销售量(kg)' },
                { id: 4, title: '登记证号' },
                { id: 5, title: '临期库存(kg)' },
                { id: 6, title: '过期处理(kg)' },
            ])
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else if (id === 2 && showId !== id) {
            setShowId(id)
            getAreaListData(areaData)
            setContentListTitle([
                { id: 1, title: '区域' },
                { id: 2, title: '经营主体' },
                { id: 3, title: '上季度销售总量' },
                { id: 4, title: '联系电话' },
                { id: 5, title: '销售台账' },
            ])
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                type: 'warning',
                content: '请勿重复操作！',
            });
        }
    };
    // 查看台账
    const getDetail = (id) => {

        navigate('/LedgerDetails', { state: { id } })
    }
    return (
        <div className={styles.pubBack}>
            {contextHolder}
            <HeaderTop title={title}></HeaderTop>
            <div className={business.contentBox}>
                {/* 左侧乡镇列表 */}
                <div className={business.leftBox}>
                    <ul className={business.topShow}>
                        {
                            titleList.map(item => {
                                return (
                                    <li key={item.id} className={showId === item.id ? `${business.show}` : ''} onClick={() => showIdClick(item.id)}>{item.title}</li>
                                )
                            })
                        }
                    </ul>
                    <LeftNav leftNavList={leftNavList} getClick={getClick} currentId={currentId}></LeftNav>
                </div>
                {/* 右侧内容区 */}
                <div className={business.right}>
                    <span className={business.topTitle}>农药用量统计列表</span>
                    <div className={business.content}>
                        {/* 经营主体 */}
                        <div className={pesticideDosageStyle.titleTop}>
                            {
                                topList.map(item => {
                                    if (showId === 1) {
                                        return (
                                            <div key={item.id} className={pesticideDosageStyle.entity} style={{ backgroundImage: `url(${item.back})` }}>
                                                <span>{item.title}</span>
                                                <span>{item.num}
                                                    <i>kg</i>
                                                </span>
                                            </div>
                                        )
                                    } else {
                                        return (
                                            <div key={item.id} className={item.id !== 1 && item.id !== 3 && item.id !== 4 ? pesticideDosageStyle.entity : pesticideDosageStyle.noShow} style={{ backgroundImage: `url(${item.back})` }}>
                                                <span>上季度销售总量</span>
                                                <span>{allWeight}
                                                    <i>kg</i>
                                                </span>
                                            </div>
                                        )
                                    }

                                })
                            }
                            <div className={showId === 1 ? pesticideDosageStyle.rightList : pesticideDosageStyle.noShow}>
                                <Input ref={keyWordsRef} value={keyWords} onChange={() => {
                                    setKeyWords(keyWordsRef.current.input.value)
                                }} placeholder="请输入农药名称查询" />
                                <Button type="primary" onClick={() => search()} icon={<SearchOutlined />}>
                                    查询
                                </Button>
                            </div>
                        </div>
                        {/* 列表 */}

                        <div className={pesticideDosageStyle.listBox}>
                            <table>
                                <thead>
                                    {
                                        contentListTitle.map(item => {
                                            return (
                                                <th key={item.id}>{item.title}  </th>
                                            )
                                        })
                                    }
                                </thead>
                                <tbody className={contentList.length !== 0 ? "" : `${pesticideDosageStyle.noShowData}`}>
                                    {
                                        contentList.map(item => {
                                            if (showId === 1) {
                                                return (
                                                    <tr key={item.certificate_code}>
                                                        <td>{item.goods_name}</td>
                                                        <td>{item.kucunNumber}</td>
                                                        <td>{item.outNumber}</td>
                                                        <td>{item.certificate_code}</td>
                                                        <td>{item.linQiNumber}</td>
                                                        <td>{item.guoQiNumber}</td>
                                                    </tr>
                                                )
                                            } else {
                                                return (
                                                    <tr key={item.id}>
                                                        <td>{item.zhen_name}</td>
                                                        <td>{item.user_name}</td>
                                                        <td>{item.weight}kg</td>
                                                        <td>{item.mobile}</td>
                                                        <td style={{ cursor: 'pointer' }} onClick={() => getDetail(item.id)}>查看台账</td>

                                                    </tr>
                                                )
                                            }

                                        })
                                    }
                                </tbody>
                                <tr className={contentList.length === 0 ? `${pesticideDosageStyle.emptyData}` : `${pesticideDosageStyle.noShowData}`}>
                                    <td colSpan={7} style={{ textAlign: 'center' }}>
                                        <Empty
                                            image="http://120.79.70.96:10301/mapimg/kong_he.png"
                                            imageStyle={{
                                                height: 150,
                                            }} />


                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    {/* 页尾 */}
                    <div className={business.pagActive}>
                        <Pagination total={total} current={areaData.pageNum} defaultCurrent={1} showTotal={(total) => `共 ${total} 条记录`} itemRender={itemRender} pageSize={10} onChange={onChangePage} showSizeChanger={false} />
                    </div>
                </div>
            </div>
        </div >
    )
}
